package com.bi.onlineEducation.service;

import com.bi.onlineEducation.dao.LoginDao;
import com.bi.onlineEducation.domain.LoginPo;
import com.bi.onlineEducation.exception.BusinessHandleException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: chenYuTao
 * @Time: 2022/1/19 20:57
 * @Description: 用户登录业务处理层
 **/
@Service
public class LoginService {

    @Resource
    private LoginDao loginDao;

    public List<LoginPo> findAll() {
        return loginDao.findAll();
    }

    public LoginPo findById(Integer id) {
        return loginDao.findById(id).get();
    }

    public LoginPo save(LoginPo loginPo) {
        if (loginPo.getLId() == null && !ObjectUtils.isEmpty(loginDao.findByLoginName(loginPo.getLoginName()))) {
            throw BusinessHandleException.buildBizException("已存在该用户名");
        }
        return loginDao.save(loginPo);
    }

    public Boolean deleteById(Integer id) {
        loginDao.deleteById(id);
        return true;
    }

    @Transactional
    public Boolean deleteByIds(List<Integer> ids) {
        for (Integer id : ids) {
            loginDao.deleteById(id);
        }
        return true;
    }

    /**
     * 用户账户密码登录
     *
     * @param loginName
     * @param password
     * @return
     */
    public LoginPo login(String loginName, String password) {
        return loginDao.login(loginName, password);
    }

    /**
     * 根据role查询所有信息
     *
     * @param role
     * @return
     */
    public List<LoginPo> findAllByRole(Integer role) {
        return loginDao.findAllByRole(role);
    }

    /**
     * 教师、普通用户条件查询
     *
     * @param realName
     * @return
     */
    public List<LoginPo> searchByRole(String realName, String address, Integer role) {
        List<LoginPo> allByRealNameLikeAndRole = loginDao.findAllByRealNameLikeAndRole("%".concat(realName).concat("%"), role);
        List<LoginPo> allByLAddressLikeAndRole = loginDao.findAllBylAddressLikeAndRole("%".concat(address).concat("%"), role);
        ArrayList<LoginPo> resultList = new ArrayList<>();
        for (LoginPo realNameVo : allByRealNameLikeAndRole) {
            for (LoginPo addressVo : allByLAddressLikeAndRole) {
                if (realNameVo.getLId() != addressVo.getLId().intValue()) continue;
                resultList.add(realNameVo);
            }
        }
        return resultList;
    }
}
